package com.army.stock.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.army.stock.domain.*;
import com.army.stock.service.*;
import com.army.stock.util.SessionUtil;
import com.javalife.common.domain.page.PaginatedArrayList;
import com.javalife.common.web.url.BaseUrl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 15/3/30.
 * 月度计划
 */
@Controller
public class ArmyMonthPlanController {

    private final static Logger logger = LoggerFactory.getLogger(ArmyMonthPlanController.class);

    @Autowired
    private ArmyDepartmentService armyDepartmentService;

    @Autowired
    private ArmyMonthplanService armyMonthplanService;

    @Autowired
    private ArmyYearplanService armyYearplanService;

    @Autowired
    private ArmyGoodService armyGoodService;

    @Autowired
    private ArmyCategoryService armyCategoryService;

    private final static String MONTH_PLANS = "monthplan/monthplans";

    private final static String NEW_MONTH_PLAN = "monthplan/new";

    private final static String MONTH_PLAN_DETAIL = "monthplan/monthPlanDetail";

    private final static String UPDATE_MONTH_PLAN = "monthplan/updateMonthPlan";

    private final static String LOAD_YEARPLAN = "monthplan/loadyearplan";

    private final static String CHOOSE_GOOD = "monthplan/choosegood";

    @RequestMapping(value = "/monthplans", method = RequestMethod.GET)
    public String monthplans(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        ArmyUser armyUser = SessionUtil.getSessionArmyUser(request);
        if (armyUser.getDepartmentId() == null) {
            logger.info("用户:{} 没有部门，无法添加月度计划", armyUser.getUserName());
            modelMap.put("noDepartment", "1");
            return MONTH_PLANS;
        }
        String departmentId = String.valueOf(armyUser.getDepartmentId());
        Map<String, Object> param = baseUrl.getQueryMap();
        param.put("departmentId", departmentId);
        ArmyDepartment armyDepartment = armyDepartmentService.getArmyDepartmentById(Long.valueOf(departmentId));
        PaginatedArrayList<ArmyMonthplan> pageInfo = armyMonthplanService.getArmyMonthplanPageInfo(
                baseUrl.getCurrentPage(), 10, param);
        modelMap.put("page", pageInfo);
        modelMap.put("baseUrl", baseUrl);
        modelMap.put("armyDepartment", armyDepartment);
        return MONTH_PLANS;
    }

    @RequestMapping(value = "/monthplans/new", method = RequestMethod.GET)
    public String addMonthplansPage(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        ArmyUser armyUser = SessionUtil.getSessionArmyUser(request);
        if (armyUser.getDepartmentId() == null) {
            modelMap.put("noDepartment", "1");
            return NEW_MONTH_PLAN;
        }
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int nextYear = currentYear + 1;
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        String departmentId = String.valueOf(armyUser.getDepartmentId());
        ArmyDepartment armyDepartment = armyDepartmentService.getArmyDepartmentById(Long.valueOf(departmentId));
        modelMap.put("armyDepartment", armyDepartment);
        modelMap.put("currentYear", currentYear);
        modelMap.put("nextYear", nextYear);
        modelMap.put("currentMonth", currentMonth);
        modelMap.put("baseUrl", baseUrl);
        return NEW_MONTH_PLAN;
    }

    @RequestMapping(value = "/monthplans/choosegood")
    public String choosegoodPage(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        String searchGoodName = request.getParameter("searchGoodName");
        Map queryMap = baseUrl.getQueryMap();
        PaginatedArrayList<ArmyGood> pageInfo = armyGoodService.getArmyGoodPageInfo(
                baseUrl.getCurrentPage(), 15, queryMap);
        List<ArmyCategory> armyCategoryList = armyCategoryService.getAllArmyCategories();
        modelMap.put("page", pageInfo);
        modelMap.put("baseUrl", baseUrl);
        modelMap.put("armyCategoryList", armyCategoryList);
        modelMap.put("searchGoodName", searchGoodName);
        modelMap.put("categoryId", StringUtils.trimToEmpty(request.getParameter("categoryId")));
        return CHOOSE_GOOD;
    }

    @RequestMapping(value = "/monthplans/loadyearplan")
    @Deprecated
    public String loadyearplan(HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        ArmyUser armyUser = SessionUtil.getSessionArmyUser(request);
        String departmentId = String.valueOf(armyUser.getDepartmentId());
        String year = request.getParameter("year");
        String searchGoodName = request.getParameter("searchGoodName");
        ArmyDepartment armyDepartment = armyDepartmentService.getArmyDepartmentById(Long.valueOf(departmentId));
        //通过部门/年得到相关的计划
        ArmyYearplan armyYearplan = armyYearplanService.getArmyYearPlanByDepartmentIdAndYear(Long.valueOf(departmentId), Integer.valueOf(year));
        if (armyYearplan != null) {
            Map map = new HashMap();
            map.put("id", departmentId);
            map.put("searchGoodName", searchGoodName);
            PaginatedArrayList page = armyYearplanService.getArmyYearplanItemsPageInfo(baseUrl.getCurrentPage(), 15, map);
            modelMap.put("page", page);
        }
        modelMap.put("armyDepartment", armyDepartment);
        modelMap.put("armyYearplan", armyYearplan);
        modelMap.put("baseUrl", baseUrl);
        modelMap.put("searchGoodName", searchGoodName);
        return LOAD_YEARPLAN;
    }

    @RequestMapping(value = "/monthplans/add", method = RequestMethod.POST)
    @ResponseBody
    public String addMonthplan(HttpServletRequest request, ModelMap modelMap) {
        String monthPlanData = request.getParameter("monthPlanData");
        logger.info("monthPlanData:{}", monthPlanData);
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            Long monthPlanId = armyMonthplanService.addArmyMonthplan(monthPlanData);
            returnMap.put("code", "0");
            returnMap.put("monthPlanId", monthPlanId);
        } catch (Exception e) {
            logger.error("addMonthplanController error:", e);
            returnMap.put("code", "-1");
        }
        return JSON.toJSONString(returnMap);
    }

    @RequestMapping(value = "/monthplans/{monthPlanId}/update", method = RequestMethod.GET)
    public String updateMonthPlan(@PathVariable(value = "monthPlanId") String monthPlanId, HttpServletRequest request, ModelMap modelMap) {
        BaseUrl baseUrl = new BaseUrl(request);
        ArmyMonthplan armyMonthplan = armyMonthplanService.getArmyMonthplanById(Long.valueOf(monthPlanId));
        if (armyMonthplan != null) {
            ArmyDepartment armyDepartment = armyDepartmentService.getArmyDepartmentById(armyMonthplan.getDepartmentId());
            Map map = new HashMap();
            map.put("monthPlanId", monthPlanId);
          //PaginatedArrayList page = armyMonthplanService.getArmyMonthplanItemsPageInfo(baseUrl.getCurrentPage(), 20, map);
            List<Map> page = armyMonthplanService.getAllArmyMonthplanItems(map);
            modelMap.put("page", page);
            modelMap.put("armyDepartment", armyDepartment);
            modelMap.put("armyMonthplan", armyMonthplan);
            modelMap.put("baseUrl", baseUrl);
        }
        return UPDATE_MONTH_PLAN;
    }

    @RequestMapping(value = "/monthplans/detail", method = RequestMethod.GET)
    public String detail(HttpServletRequest request, ModelMap modelMap) {
        String monthPlanId = request.getParameter("id");
        BaseUrl baseUrl = new BaseUrl(request);
        ArmyMonthplan armyMonthplan = armyMonthplanService.getArmyMonthplanById(Long.valueOf(monthPlanId));
        if (armyMonthplan != null) {
            ArmyDepartment armyDepartment = armyDepartmentService.getArmyDepartmentById(armyMonthplan.getDepartmentId());
            Map map = new HashMap();
            map.put("monthPlanId", monthPlanId);
            //   PaginatedArrayList page = armyMonthplanService.getArmyMonthplanItemsPageInfo(baseUrl.getCurrentPage(), 20, map);
            List<Map> page = armyMonthplanService.getAllArmyMonthplanItems(map);
            modelMap.put("page", page);
            modelMap.put("armyDepartment", armyDepartment);
            modelMap.put("armyMonthplan", armyMonthplan);
            modelMap.put("baseUrl", baseUrl);
        }
        return MONTH_PLAN_DETAIL;
    }

    //判断商品在月度明细里是否存在
    @RequestMapping(value = "/monthplans/checkExist", method = RequestMethod.POST)
    @ResponseBody
    public String checkExist(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            String goodid = request.getParameter("goodid");
            String monthPlanId = request.getParameter("monthPlanId");
            if (armyMonthplanService.checkExist(Long.valueOf(monthPlanId), Long.valueOf(goodid))) {
                returnMap.put("code", "1");
            } else {
                //不存在,可以放进去
                returnMap.put("code", "0");
            }
        } catch (Exception e) {
            returnMap.put("code", "-1");
            logger.error("checkExist error:", e);
        }
        return JSON.toJSONString(returnMap);
    }

    //修改月度计划
    @RequestMapping(value = "/monthplans/update", method = RequestMethod.POST)
    @ResponseBody
    public String updateMonthPlan(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> returnMap = new HashMap<String,Object>();
        try {
            String monthPlanData = request.getParameter("monthPlanData");
            logger.info("修改年度计划参数:{}", monthPlanData);
            JSONObject json = JSON.parseObject(monthPlanData);
            returnMap = armyMonthplanService.updateArmyMonthplan(json);
            if (returnMap == null) {
                returnMap.put("code", "-1");
            } else {
                returnMap.put("code", "0");
            }
        } catch (Exception e) {
            returnMap.put("code", "-1");
            logger.error("updateMonthPlan error:", e);
        }
        return JSON.toJSONString(returnMap);
    }

    @RequestMapping(value = "/monthplans/applyMonthPlan", method = RequestMethod.POST)
    @ResponseBody
    public String applyMonthPlan(HttpServletRequest request, ModelMap modelMap) {
        Map<String, String> returnMap = new HashMap<>();
        String monthPlanId = request.getParameter("monthPlanId");
        String status = request.getParameter("status");
        Map<String, Object> param = new HashMap<String, Object>();
        try {
            armyMonthplanService.applyArmyMonthplan(Long.valueOf(monthPlanId), Integer.valueOf(status));
            returnMap.put("code", "0");
        } catch (Exception e) {
            logger.error("applyMonthPlan error:" + e.getMessage());
            returnMap.put("code", "-1");
        }
        return JSON.toJSONString(returnMap);
    }

}
